package ck.tool.stocksmart;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class StockQuoteDBAdapter {
  private static final String DATABASE_NAME = "stockquote.db";
  private static final String DATABASE_TABLE = "stockItems";
  private static final int DATABASE_VERSION = 1;
 
  public static final String KEY_ID = "_id";
  public static final String KEY_STOCK = "stock_code";
  public static final String KEY_CREATION_DATE = "creation_date";
  public static final String KEY_CURRENT_PRICE = "current_price";
  public static final String KEY_FIRST_FOCUS_PRICE= "first_focus_price";
  public static final String KEY_RISE_PRICE = "rise_price";
  public static final String KEY_DROP_PRICE = "drop_price";
  //once I got one idea,add the table here!
  
  private static SQLiteDatabase db  = null;
  private Context context;
  private toDoDBOpenHelper dbHelper;

  public StockQuoteDBAdapter(stocksmart _stocksmart) {
	this.context = _stocksmart;
	dbHelper = new toDoDBOpenHelper(context, DATABASE_NAME, 
            null, DATABASE_VERSION);
	
}

public StockQuoteDBAdapter(StockAlarm stockAlarm) {
	this.context = stockAlarm;
    dbHelper = new toDoDBOpenHelper(context, DATABASE_NAME, 
                                    null, DATABASE_VERSION);
}

public StockQuoteDBAdapter(StockAlarmService stockAlarmService) {
	this.context = stockAlarmService;
    dbHelper = new toDoDBOpenHelper(context, DATABASE_NAME, 
                                    null, DATABASE_VERSION);
}

public void StockQuoteBAdapter(Context context) {
	this.context = context;
    dbHelper = new toDoDBOpenHelper(context, DATABASE_NAME, 
                                    null, DATABASE_VERSION);
    
  }
  
  public void close() {
    db.close();
  }
  
  public void open() throws SQLiteException {  
    try {
      db = dbHelper.getWritableDatabase();
    } catch (SQLiteException ex) {
      db = dbHelper.getReadableDatabase();
    }
  }  
  
  //Insert a new task
  public long insertStock(StockFormat _stock) {
    // Create a new row of values to insert.
    ContentValues newStockValues = new ContentValues();
    // Assign values for each row.
    newStockValues.put(KEY_STOCK, _stock.getStock());
    newStockValues.put(KEY_CREATION_DATE, _stock.getCreated().getTime());
    newStockValues.put(KEY_CURRENT_PRICE, _stock.getCurrentPrice());
    newStockValues.put(KEY_FIRST_FOCUS_PRICE, _stock.getFirstFocusPrice());
    Log.v("test db",_stock.toString());
    newStockValues.put(KEY_RISE_PRICE, _stock.getRisePrice());
    newStockValues.put(KEY_DROP_PRICE, _stock.getDropPrice());
    
    // Insert the row.
    opened();
    return db.insert(DATABASE_TABLE, null, newStockValues);
  }

  // Remove a task based on its index
  public boolean removebyIndex(long _rowIndex) {
	//Add for test
	Log.v("Test the delet function", "The index wanted to delet is " + String.valueOf(_rowIndex));
	opened();
    return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
  }

  // Remove a task based on its task
  public boolean removeByStock(String _stock) {
	//Add for test
	Log.v("Delete the stock is ", _stock);
	opened();
	return db.delete(DATABASE_TABLE, KEY_STOCK + "=" +"\""+ _stock +"\"", null) > 0;
  }
  // Update a task
  public boolean updateCurrentPrice(String _stock, float _current_price) {
    ContentValues newValue = new ContentValues();
    newValue.put(KEY_CURRENT_PRICE, _current_price);
    Log.v("Test the updatedb", _stock.trim());
    opened();
    return db.update(DATABASE_TABLE, newValue,KEY_STOCK + "=" +"\""+ _stock +"\"", null) > 0;
  }
  
  public boolean updateRisePrice(String _stock, float _rise_price) {
    ContentValues newValue = new ContentValues();
    newValue.put(KEY_RISE_PRICE, _rise_price);
    opened();
    return db.update(DATABASE_TABLE, newValue,KEY_STOCK + "=" +"\""+ _stock +"\"", null) > 0;
  }
  
  public boolean updateDropPrice(String _stock, float _drop_price) {
    ContentValues newValue = new ContentValues();
    newValue.put(KEY_DROP_PRICE, _drop_price);
    opened();
    return db.update(DATABASE_TABLE, newValue, KEY_STOCK + "=" +"\""+ _stock +"\"", null) > 0;
  }
  
  // Add for delete fluent
  public Cursor setCursorToKeyStock(String _stock) throws SQLException {
	  Cursor result = db.query(true, DATABASE_TABLE,
			                   new String[] {KEY_ID, KEY_STOCK},
			                   KEY_STOCK + "=" +"\""+ _stock +"\"", null, null, null,
			                   null,null);
	  if((result.getCount() == 0) || !result.moveToFirst()) {
		  throw new SQLException("No Key_STOCK items find for now: " + _stock);
	  }
	  return result;
  }
  public Cursor getAllStockFormatCursor() {
	opened();
    return db.query(DATABASE_TABLE, 
                    new String[] { KEY_ID, KEY_STOCK, KEY_CREATION_DATE, KEY_CURRENT_PRICE, KEY_FIRST_FOCUS_PRICE, KEY_RISE_PRICE, KEY_DROP_PRICE}, 
                    null, null, null, null, null);
  }

  public Cursor setCursorToStockFormat(long _rowIndex) throws SQLException {
	opened();
    Cursor result = db.query(true, DATABASE_TABLE, 
	                           new String[] {KEY_ID, KEY_STOCK},
                             KEY_ID + "=" + _rowIndex, null, null, null, 
                             null, null);
    if ((result.getCount() == 0) || !result.moveToFirst()) {
      throw new SQLException("No stock found for row: " + _rowIndex);
    }
    return result;
  }

  public StockFormat getToStock(String _stock) throws SQLException {
	opened();
    Cursor cursor = db.query(true, DATABASE_TABLE, 
                             new String[] {KEY_ID, KEY_STOCK,KEY_CREATION_DATE,KEY_CURRENT_PRICE,KEY_FIRST_FOCUS_PRICE,KEY_RISE_PRICE,KEY_DROP_PRICE},
                             KEY_STOCK + "=" +"\""+ _stock +"\"", null, null, null, 
                             null, null);
    if ((cursor.getCount() == 0) || !cursor.moveToFirst()) {
      throw new SQLException("No stock item found for row: " + _stock);
    }

    String stock = cursor.getString(cursor.getColumnIndex(KEY_STOCK));
    long created = cursor.getLong(cursor.getColumnIndex(KEY_CREATION_DATE));
    float current_price = cursor.getFloat(cursor.getColumnIndex(KEY_CURRENT_PRICE));
    float first_focus_price = cursor.getFloat(cursor.getColumnIndex(KEY_FIRST_FOCUS_PRICE));
    float rise_price = cursor.getFloat(cursor.getColumnIndex(KEY_RISE_PRICE));
    float drop_price = cursor.getFloat(cursor.getColumnIndex(KEY_DROP_PRICE));
		  
    StockFormat result = new StockFormat(stock, new Date(created), current_price, first_focus_price, rise_price, drop_price);
    return result;  
  }
  public void opened()
  {
	  if(db == null || !db.isOpen())
	    {
	    	db = dbHelper.getWritableDatabase();
	    }
  }
  
  private static class toDoDBOpenHelper extends SQLiteOpenHelper {

	  public toDoDBOpenHelper(Context context, String name,
	                          CursorFactory factory, int version) {
	    super(context, name, factory, version);
	  }

	  // SQL Statement to create a new database.
	  private static final String DATABASE_CREATE = "create table " + 
	    DATABASE_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
	    KEY_STOCK + " text not null, " + KEY_CREATION_DATE + " long, " + KEY_CURRENT_PRICE + " float," + 
	    KEY_FIRST_FOCUS_PRICE +" float," + KEY_RISE_PRICE + " float," + KEY_DROP_PRICE + " float);";

	  @Override
	  public void onCreate(SQLiteDatabase _db) {
	    _db.execSQL(DATABASE_CREATE);
	  }

	  @Override
	  public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
	    Log.w("TaskDBAdapter", "Upgrading from version " + 
	                           _oldVersion + " to " +
	                           _newVersion + ", which will destroy all old data");

	    // Drop the old table.
	    _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
	    // Create a new one.
	    onCreate(_db);
	  }
	}
}